package com.findsing.jetty.websocket.client.endpoints;

import java.io.IOException;
import java.util.List;

import javax.websocket.ClientEndpoint;
import javax.websocket.EncodeException;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.ws.rs.core.NewCookie;

import org.apache.log4j.Logger;

import com.findsing.jetty.websocket.model.HandShake;
import com.findsing.jetty.websocket.model.Message;
import com.findsing.jetty.websocket.util.Coder.MessageDecoder;
import com.findsing.jetty.websocket.util.Coder.MessageEncoder;

@ClientEndpoint( encoders = { MessageEncoder.class }, decoders = { MessageDecoder.class }, configurator = ClientEndpointConfigurator.class)
public class BroadcastClientEndpoint {
	private static final Logger logger = Logger.getLogger(BroadcastClientEndpoint.class.getName());

	@OnOpen
	public void onOpen(final Session session, EndpointConfig config) throws IOException, EncodeException {
		List<NewCookie> cookies = ClientEndpointConfigurator.getCookies();
		String sessionId = null;
		for(NewCookie cookie: cookies)
		{
			if(cookie.getName().equals("JSESSIONID"))
			{
				sessionId = cookie.getValue();
			}
		}

		HandShake handShake = new HandShake();
		handShake.setJsessionId(sessionId);
		//session.getBasicRemote().sendObject(new Message("Greeting", "{\"JSESSIONID\": \"" + sessionId + "\"}"));
		session.getBasicRemote().sendObject(new Message("Greeting", handShake.toString()));
	}

	@OnMessage
	public void onMessage(final Message message, final Session session) {
		logger.info(String.format("Client received message '%s' from '%s'", message.getMessageBody(), message.getMessageName()));
	}
	
	@OnClose
	public void onClose(final Session session)
	{
		logger.info("Session is closing...");
	}
	
	@OnError
	public void onError(final Throwable t, final Session session)
	{
		logger.error(t.getMessage(), t);
	}
}

